let mysql = require("mysql2/promise")
//数据库配置
let config = {
    host:'localhost',
    database:'sequelize01',
    user:'root',
    password:'123456'
}
//通过命令行获取参数
//例如:node auto.js -host localhost -database sequelize01 -user root -password 123456 -table swiper
let args = process.argv;
let tables = null;
if(args.length<10){
    console.log("参数数量不够，执行全库生成");
}
else{
    //前面两个元素是指node路径和当前文件的路径，需要删除
    args = args.splice(2);
    //循环数组，把数组形式的参数处理成对象形式的参数
    args.forEach((item,index)=>{
        let i = index+1;
        //奇数位置的元素作为对象属性名
        if(i%2!=0){
            //参数名横杠不能作为变量名的首字符，要去掉
            item = item.replace("-","")
            //偶数位置的元素作为对象的属性值
            //除了表名以外的参数，放入到config中
            if(item!="table"){
                config[item]=args[index+1]
            }
            else{
                //表名参数的值转换为数组
                //格式:
                //['attribute']
                tables = args[index+1].split(",")
            }
        }
    });
}

//把表名转换为驼峰命名法的形式
function toHump(tableName){
    let name = tableName.replace(/\_(\w)/g,function(arg){
        return arg.toUpperCase()
    })
    return name.replace("_","");
}
//把表名转换为pascal命名法形式
function toPasc(tableName){
    return tableName.slice(0,1).toUpperCase()+tableName.slice(1)
}
//引入ejs模板库
let ejs = require("ejs")
//引入fs库，操作文件用
let fs = require("fs")
let main = async function(){
    try {
        //创建数据库连接对象
        let connection = await mysql.createConnection(config)

        if(!tables){
            //定义查询所有表名的sql
            let tableNameSql = "select table_name from information_schema.tables where table_schema = '"+config.database+"'";
            tables = await connection.execute(tableNameSql)
            //所有表名的数组
            //数据格式:
            //[{ table_name: 'attribute' }]
            tables = JSON.parse(JSON.stringify(tables[0]))
        }
        let appReqRouterContent=""
        let appUserRouterContent=""
        for (let index = 0; index < tables.length; index++) {
            //比如: [{ table_name: 'attribute' }] || ['attribute']
            let tableName = tables[index].table_name||tables[index];

            //根据英文表名查询中文表名
            let getCnTableNameSql = "SELECT table_comment "
            +"FROM information_schema.tables "
            +"WHERE table_schema = '"+config.database+"' "
            +"AND table_name='"+tableName+"'";
            let cnTableName = await connection.execute(getCnTableNameSql)
            cnTableName = JSON.parse(JSON.stringify(cnTableName))
            cnTableName = cnTableName[0][0].table_comment
            cnTableName = cnTableName.replace('表','管理')
          
            //把表名转换为驼峰命名法
            let humpTableName = toHump(tableName)
            //把表名转换为pascal命名法
            let pascTableName = toPasc(humpTableName)

            //根据表名查询表拥有的所有字段信息
            let selTableInfoSql = "SELECT COLUMN_NAME,DATA_TYPE,COLUMN_COMMENT "
            +"FROM information_schema.`COLUMNS` "
            +"WHERE table_schema='"+config.database+"' AND table_name='"+tableName+"'";
            let columnInfo = await connection.execute(selTableInfoSql)
            columnInfo = JSON.parse(JSON.stringify(columnInfo))
            columnInfo = columnInfo[0]
            columnInfo.forEach(item=>{
                if(item.DATA_TYPE=="varchar"){
                    item.DATA_TYPE = "string"
                }
                else if(item.DATA_TYPE=="int"){
                    item.DATA_TYPE = "integer"
                }
            })
           
            //把准备好的表名注入到控制器模板中
            let controllerContent = await ejs.renderFile("./automake/controller.ejs",
            {humpTableName:humpTableName,tableName:tableName})
            //把生成好的控制器内容，生成文件
            fs.writeFileSync("./automake/controllers/"+pascTableName+"Controller.js",controllerContent)
            
            //把准备好的表名注入到路由模板中，生成路由内容
            let routerContent = await ejs.renderFile("./automake/router.ejs",
            {humpTableName,tableName,
            pascTableName,columnInfo,cnTableName})

            //把准备好的路由内容写入到指定位置的文件中
            fs.writeFileSync("./automake/routes/api/"+tableName+"_router.js",routerContent)
            //生成app.js中引入的路由路径对象
            //例如：var goodsRouter = require('./routes/api/goods_router.js');
            appReqRouterContent += await ejs.renderFile("./automake/appreqrouter.ejs",
            {humpTableName:humpTableName,tableName:tableName})+"\r\n";
            //生成app.js中定义的路由路径内容
            //例如：app.use('/goods',goodsRouter);
            appUserRouterContent += await ejs.renderFile("./automake/appuserouter.ejs",
            {humpTableName:humpTableName,tableName:tableName})+"\r\n";
           
        }
        /*
        fs.writeFileSync("./automake/appjs/"+"appreqrouter.js",appReqRouterContent);
        fs.writeFileSync("./automake/appjs/"+"appuserouter.js",appUserRouterContent);*/
        console.log("生成完毕");
        process.exit();
    } catch (error) {
        console.log(error)
    }
    

}

main()

